package com.loooooo.pm2024.modules.sys.service;


import com.loooooo.pm2024.modules.sys.selector.UserSelector;
import com.loooooo.pm2024.modules.sys.mapper.UserMapper;
import com.loooooo.pm2024.modules.sys.model.User;
import com.loooooo.pm2024.security.PasswordEncoder;
import com.loooooo.pm2024.security.SecurityUtils;
import com.loooooo.pm2024.service.IdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    IdService idService;

    @Autowired
    PasswordEncoder passwordEncoder;


    public List<User> list(UserSelector selector) {
        return userMapper.select(selector);
    }

    public int count(UserSelector selector) {
        return userMapper.count(selector);
    }

    public int update(User user) {
        long now = System.currentTimeMillis();
        Long  userId= SecurityUtils.loginedUserId();
        user.setUpdatedAt(now);
        user.setUpdatedBy(userId);
        if (StringUtils.hasText(user.getNewPassword())) {
            user.setPasswordPlaintext(user.getNewPassword());
            String newPassword = passwordEncoder.encode(user.getNewPassword());
            user.setPassword(newPassword);
        }
        if (user.getId() == null || user.isNewEntity() || user.getId() <= 0L) {
            if (user.getId() == null || user.getId() <= 0L) {
                user.setId(idService.nextId());
            }
            user.setCreatedAt(now);
            user.setCreatedBy(userId);
            userMapper.insert(user);
        }
        return userMapper.update(user);
    }
}
